package cn.eric.framework.utils;

import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

/**
 * 提供读取配置文件的方法
 * Created by Eric on 2017/7/2.
 */
public class CfgUtil {
    private CfgUtil() {
    }

    public static <T> T JAXBParser(Class<T> c, String path) throws IllegalAccessException, InstantiationException, JAXBException {
        T result = c.newInstance();
        if (path != null) {
            JAXBContext jaxbContext = JAXBContext.newInstance(result.getClass());
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            result = (T) unmarshaller.unmarshal(CfgUtil.class.getResourceAsStream(path));
        }
        return result;
    }

    public static boolean validateXMLWithSchema(String xsdPath, String xmlPath) throws SAXException, IOException, URISyntaxException {
        try {
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(CfgUtil.class.getResource(xsdPath).toURI()));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new File(CfgUtil.class.getResource(xmlPath).toURI())));
        } catch (IOException | URISyntaxException | SAXException e) {
            throw e;
        }
        return true;
    }
}